<?php
/**
 * Created by PhpStorm.
 * User: Ysll <754060604@qq.com>
 * Date: 2017/9/7
 * Time: 11:31
 */

function getTopicCategory()
{
    $db = require 'DatabaseService.php';
    $result = mysqli_query($db, "SELECT `id`, `title` FROM `topics_category` WHERE `is_enable` = TRUE AND `is_deleted` = FALSE");
    return mysqli_fetch_all($result, MYSQLI_ASSOC);
}

/**
 * @param $category_id
 * @return array|null
 */
function getTopicCategoryById($category_id)
{
    $db = require 'DatabaseService.php';
    $result = mysqli_query($db, "SELECT * FROM `topics_category` WHERE is_deleted = FALSE AND id = {$category_id}");

    if ($result === false) {
        return [];
    }
    return mysqli_fetch_assoc($result);
}

/**
 * @param $question
 * @param $page
 * @param int $limit
 * @return object
 */
function getCategoryPagination($page, $question, $limit = 20)
{
    $db = require 'DatabaseService.php';
    $categories = new stdClass();
    $result = mysqli_query($db, "SELECT count(*) count FROM topics_category WHERE is_deleted = FALSE AND title LIKE '%{$question}%'");
    $categories->total = mysqli_fetch_assoc($result)['count'];
    $categories->per_page = $limit;
    $categories->current_page = $page;
    $categories->last_page = (int)ceil($categories->total / $categories->per_page);
    $start = $categories->per_page * $categories->current_page - $categories->per_page;
    $result = mysqli_query($db, "SELECT * FROM topics_category WHERE is_deleted = FALSE AND title LIKE '%{$question}%' LIMIT $start,{$limit}");
    $categories->items = mysqli_fetch_all($result, MYSQLI_ASSOC);
    return $categories;
}

/**
 * @param $id
 * @param array $data
 * @return bool
 */
function updateCategory($id, $data)
{
    $sql = 'UPDATE topics_category SET';
    foreach ($data as $key => $value) {
        $sql .= " $key = '$value',";
    }
    $sql = rtrim($sql, ',') . " WHERE id = $id";
    $db = require 'DatabaseService.php';
    $result = mysqli_query($db, $sql);
    if ($result == false || mysqli_errno($db)) {
        $_SESSION['error_code'] = mysqli_errno($db);
        $_SESSION['error_data'] = mysqli_error($db);
        return false;
    }
    return true;
}

function createCategory($data)
{
    $db = require 'DatabaseService.php';
    $k = '';
    $v = '';
    foreach ($data as $key => $value) {
        $value = mysqli_real_escape_string($db, $value);
        $k .= "`$key`,";
        $v .= "'$value',";
    }
    $k = rtrim($k, ',');
    $v = rtrim($v, ',');
    $sql = "INSERT INTO topics_category ({$k}) VALUES ({$v})";
    $result = mysqli_query($db, $sql);
    if ($result == false || mysqli_errno($db)) {
        $_SESSION['error_code'] = mysqli_errno($db);
        $_SESSION['error_data'] = mysqli_error($db);
        return false;
    }
    return true;
}